<?php

namespace app\common\model;

use think\facade\Cache;
use think\Model;

/**
 * 我的租房
 */
class UserHouse extends BaseModel
{

    // 表名,不含前缀
    protected $name = 'user_house';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = "datetime";
    // 定义时间戳字段名
    protected $updateTime = false;

    public function house()
    {
        return $this->belongsTo("house", "house_id")->setEagerlyType(0);
    }

    public function user()
    {
        return $this->belongsTo("user", "user_id")->setEagerlyType(0);
    }

    public function getUserCurrentHouse($userId)
    {
        $nowTime = date("Y-m-d H:i:s");
        $dataList = $this->where("user_id", $userId)->where("expire_time", ">=", $nowTime)->where("create_time", "<=", $nowTime)->select();
        if (empty($dataList)) return [];
        foreach ($dataList as $key => $value) {
            $dataList[$key] = $this->_decodeData($value);
        }
        return $dataList;
    }


    public function getUserHouse($userId, $page, $limit)
    {
        $dataList = $this->where("user_id", $userId)->order("id", "desc")->limit($page, $limit)->select();
        foreach ($dataList as $key => $value) {
            $dataList[$key] = $this->_decodeData($value);
        }
        return $dataList;
    }

    private function _decodeData($findData)
    {
        $findData['type'] = model("UserHouseType")->get($findData["type_id"]);
        $findData['house'] = model('house')->selectById($findData['house_id'], true);
        $findData['title'] = $findData['house']['title'];
        $userInfo = model('user')->findById($findData['user_id']);
        $findData["bill"] = model("user_house_bill")->where("user_house_id", $findData["id"])->select()->toArray();
        $findData['user'] = [
            'id' => $userInfo['id'],
            'nickname' => $userInfo['nickname'],
            'phone' => $userInfo['phone'],
            'wx_avatar' => $userInfo['wx_avatar']
        ];
        return $findData;
    }


    public function selectById($id)
    {
        $findData = $this->findById($id);
        return $this->_decodeData($findData);
    }


}
